﻿namespace Leetcode.N0385;
public class Solution
{
    public NestedInteger Deserialize(string s)
    {
        NestedInteger result = null;
        var stack = new Stack<NestedInteger>();
        for (int i = 0; i < s.Length; i++)
        {
            switch (s[i])
            {
                case '[':
                    var n = new NestedInteger();
                    if (stack.Count > 0)
                    {
                        stack.Peek().Add(n);
                    }
                    stack.Push(n);
                    break;
                case ']':
                    result = stack.Pop();
                    break;
                case ',':
                    break;
                default:
                    var val = this.ReadInteger(s, ref i);
                    if (stack.Count == 0)
                    {
                        result = val;
                    }
                    else
                    {
                        stack.Peek().Add(val);
                    }
                    break;
            }

        }
        return result;
    }

    private NestedInteger ReadInteger(string s, ref int index)
    {
        var val = 0;
        bool isMinus;
        if (s[index] == '+')
        {
            isMinus = false;
        }
        else if (s[index] == '-')
        {
            isMinus = true;
        }
        else
        {
            isMinus = false;
            val = s[index] - '0';
        }
        var i = index;
        while (i < s.Length - 1)
        {
            var next = s[i + 1];
            if (next >= '0' && next <= '9')
            {
                val = val * 10 + next - '0';
                index++;
            }
            else
            {
                break;
            }
            i++;
        }
        return new NestedInteger(isMinus ? (0 - val) : val);
    }
}
